# include <reg52.h>
sbit DS1302IO=P3^5;
sbit DS1302CLK=P3^4;
sbit DS1302RST=P3^3;

void DS1302WriteByte(unsigned char Data)
{
    unsigned char i;
    for(i=8;i>0;i--)
    {
        Data>>=1;
        DS1302IO=CY;
        DS1302CLK=1;
        DS1302CLK=0;
    }
}

unsigned char DS1302ReadByte()
{
    unsigned char i,temp=0;
    for(i=0;i<8;i++)
    {
        DS1302CLK = 0;
        if(DS1302IO!=0) temp|= (1<<i);
        DS1302CLK=1;
    }
    return(temp);
}

void DS1302Write(unsigned char Address,unsigned char Data)
{
    DS1302RST=0;
    DS1302CLK=0;
    DS1302RST=1;
    DS1302WriteByte(Address);
    DS1302WriteByte(Data);
    DS1302CLK=1;
    DS1302RST=0;
}

unsigned char DS1302Read(unsigned char Address)
{
    unsigned char Data;
    DS1302RST=0;
    DS1302CLK=0;
    DS1302RST=1;
    DS1302WriteByte(Address);
    Data = DS1302ReadByte();
    DS1302CLK=1;
    DS1302RST=0;
    return(Data);
}

void DS1302GetDateTime(unsigned char DateTime[])
{
    unsigned char i;
    unsigned char Address=0x81;
    for(i=0;i<7;i++)
    {
        DateTime[i] = DS1302Read(Address);
        Address += 2;
    }
}

void DS1302SetDateTime(unsigned char DateTime[])
{
    unsigned char i;
    unsigned char Address=0x80;
    DS1302Write(0X8e,0x00);
    for(i=0;i<7;i++)
    {
        DS1302Write(Address,DateTime[i]);
        Address += 2;
    }
    DS1302Write(0x8e,0x80);
}